Date.prototype.Format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'h+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'q+': Math.floor((this.getMonth() + 3) / 3),
    'S': this.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
  return fmt;
}

function getRandomColor() {
  var letters = 'ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 6)];
  }
  return color;
}

function unique(arr) {
  if (!Array.isArray(arr)) {
    console.log('type error!')
    return;
  }
  let arrry = [arr[0]];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i].assignee !== arr[i - 1].assignee) {
      arrry.push(arr[i]);
    }
  }
  return arrry;
}

function insertAfter(newNode, referenceNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

function makeTask(records, config) {
  let tasks = []
  for (let i = 0; i < records.length; i++) {
    console.log(records[i][config.endDate].value)
    tasks.push({
      start: records[i][config.startDate].value,
      end: records[i][config.endDate].value,
      name: records[i][config.title].value,
      id: records[i].$id.value,
      progress: records[i][config.progress].value,
      assignee: getFirstAssigneeName(records[i])
    })
  }
  tasks.sort((one, two) => {
    if (one.assignee < two.assignee) {
      return 1
    } else {
      return -1
    }
  })
  console.log(tasks)
  return tasks
}

function updateTaskDate(ko, rocodeId, startDate, endDate) {
  var params = {
    app: 60,
    id: rocodeId,
    record: {
      start_date: {
        value: startDate
      },
      end_date: {
        value: endDate
      }
    }
  };
  ko.api(ko.api.url('/k/v1/record', true), 'PUT', params).then(function (resp) {}, function (error) {});
}

function updateTaskProgress(ko, rocodeId, progressName, progress) {
  record = {};
  record[progressName] = {
    value: progress
  };

  var params = {
    app: 60,
    id: rocodeId,
    record
  };
  console.log(params);
  ko.api(ko.api.url('/k/v1/record', true), 'PUT', params).then(function (resp) {}, function (error) {});
}

function getFirstAssigneeName(r) {
  for (const i in r) {
    if (r[i].type === 'STATUS_ASSIGNEE') {
      if (r[i].value.length > 0) {
        return r[i].value[0].name;
      } else {
        return 'nobody';
      }
    }
  }
}